#include "Define.h"

#include <cstdio>
#include <cstdlib>
#include <cmath>

#include <vector>
#include <fstream>
#include <string>
#include <map>

using namespace std;

#include <GL/glew.h>
#include <GL/glfw.h>

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>

using namespace glm;

#include "TextureRGB.h"

bool TextureRGB::init(const std::string& path)
{
	unsigned char* buffer = new unsigned char[2048*2048*3];

	std::ifstream file(path.c_str(), ios::in|ios::binary|ios::ate);

	if (!file.is_open())
		printf("Fail");
	ifstream::pos_type size = file.tellg();
	file.seekg(0, ios::beg);
	file.read(reinterpret_cast<char*>(buffer), size);
	file.close();

	glGenTextures(1, &Texture);

	glBindTexture(GL_TEXTURE_2D, Texture);
	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2048, 2048, 0, GL_RGB, GL_UNSIGNED_BYTE, buffer);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); 
	glGenerateMipmap(GL_TEXTURE_2D);
	
	delete[] buffer;

	return true;
}

void TextureRGB::destroy()
{
	glDeleteTextures(1, &TextureID);
}

void TextureRGB::activate(const GLuint& idx)
{
	glActiveTexture(GL_TEXTURE0 + idx);
	glBindTexture(GL_TEXTURE_2D, Texture);
}